package fun.qu_an.minecraft.velocity.mgh;

import com.google.inject.Inject;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.ServerConnectedEvent;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
import fun.qu_an.minecraft.velocity.mgh.config.MGHConfig;
import lombok.Getter;
import org.slf4j.Logger;

@Plugin(
	id = BuildConstants.PLUGIN_ID,
	name = BuildConstants.PLUGIN_NAME,
	version = BuildConstants.VERSION
)
public class MiniGamesHelper {
	public static final ChannelIdentifier FORCE_OPTIONS = MinecraftChannelIdentifier.create(BuildConstants.PLUGIN_ID, "force_options");
	@Getter
	private static MiniGamesHelper instance;
	@Getter
	@Inject
	private Logger logger;
	@Getter
	@Inject
	private ProxyServer proxyServer;

	MiniGamesHelper() {
		instance = this;
	}

	@Subscribe
	public void onProxyInitialization(ProxyInitializeEvent event) {
		MGHConfig.reload();
		proxyServer.getCommandManager().register(new BrigadierCommand(LiteralArgumentBuilder
			.<CommandSource>literal("vmghreload")
			.requires(source -> source.hasPermission("mgh.admin"))
			.executes(context -> {
				MGHConfig.reload();
				return 1;
			})));
	}

	@Subscribe
	public void onServerJoin(ServerConnectedEvent event) {
		Player player = event.getPlayer();
		String serverName = event.getServer().getServerInfo().getName();
		byte[] bytes = MGHConfig.getSerialized(serverName);
		player.sendPluginMessage(FORCE_OPTIONS, bytes);
		logger.info("Send force options of server {} to player {}", serverName, player.getUsername());
	}
}
